package util.toolkit;

import java.sql.Timestamp;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {
	/*
	 * 将一个日期格式的字符串装换为对应的Timestamp对象
	 * toTimestamp("1982-12-02 9:26:44"); 
	 * toTimestamp("1982-12-02");
	 */
	public static Timestamp toTimestamp(String date){
		try {
			if(date.length()>10 && date.indexOf(":")>0){ //用该算法识别日期字符串中是否拥有时间内容
				Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date d = (Date)f.parseObject(date); 
				Timestamp ts = new Timestamp(d.getTime());
				return ts;
			}
			else{
				Format f = new SimpleDateFormat("yyyy-MM-dd");
				Date d = (Date)f.parseObject(date); 
				Timestamp ts = new Timestamp(d.getTime());
				return ts;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 将一个日期格式的date对象装换为对应的Timestamp对象
	 */
	public static Timestamp toTimestamp(Date date){
		Timestamp ts = new Timestamp(date.getTime());
		return ts;
	}
	
	/*
	 * 将一个日期格式的字符串装换为对应的Date对象
	 * toDate("1982-12-02 9:26:44"); 
	 * toDate("1982-12-02");
	 */
	public static Date toDate(String date){
		try {
			if(date.length()>10 && date.indexOf(":")>0){ //用该算法识别日期字符串中是否拥有时间内容
				Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date d = (Date)f.parseObject(date); 
				return d;
			}
			else{
				Format f = new SimpleDateFormat("yyyy-MM-dd");
				Date d = (Date)f.parseObject(date); 
				return d;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 将一个日期格式的字符串装换为对应的Calendar对象
	 * Calendar("1982-12-02 9:26:44"); 
	 * Calendar("1982-12-02");
	 */
	public static Calendar toCalendar(String date){
		try {
			if(date.length()>10 && date.indexOf(":")>0){ //用该算法识别日期字符串中是否拥有时间内容
				Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date d = (Date)f.parseObject(date); 
				Calendar cal = Calendar.getInstance();
				cal.setTime(d);
				return cal;
			}
			else{
				Format f = new SimpleDateFormat("yyyy-MM-dd");
				Date d = (Date)f.parseObject(date); 
				Calendar cal = Calendar.getInstance();
				cal.setTime(d);
				return cal;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 将yyyy/MM/dd的日期格式转换为yyyy-MM-dd格式
	 * @param oldtime 要转换的日期
	 * @return 返回转化后的日期
	 * @throws ParseException
	 */
	public static String formatConversion(String oldtime){
		SimpleDateFormat in = new SimpleDateFormat("yyyy/MM/dd");
		SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd");
		try {
			in.format(oldtime);
			return out.format(in.format(oldtime));
		} catch (Exception e) {
			e.printStackTrace();
			return oldtime;			
		}
	}
}
